import socketserver
from Log import log
import datetime
import os
import json

datetime_format = "%Y/%m/%d %H:%M:%S"
config_path = "/home/ubuntu/gas_recycler_server/SensorMonitor/modules/port_monitor_config.json"
log_path = None
host = None
port = None

with open(config_path, "r") as f:
	config = json.loads(f.read())
	log_path = config['log_path']
	host = config['address']['ip']
	port = config['address']['port']
	f.close()


class PortMonitorServer(socketserver.BaseRequestHandler):
	def handle(self) -> None:
		log.print("\n = = = = = = = = = = =")
		log.print("[Time]:", datetime.datetime.now().strftime(datetime_format))
		log.print("[Connection Started]:\n", self.request)
		log.print("[Address]:", self.client_address)

		while True:
			raw = self.request.recv(1024)
			log.print("\n[Time]:", datetime.datetime.now().strftime(datetime_format))
			log.print("[Received Data]: ")
			log.print("[Raw]: \n", raw)
			# try:
			# 	buf = b''
			# 	for b in raw:
			# 		buf += b
			# 		print(buf)
			# 		if len(buf) == 2:
			# 			log.print("[HEX]: ", hex(ord(buf)))
			# 			buf = b''
			# except TypeError as e:
			# 	log.print("[NOT HEX]: ", e.args)

			try:
				log.print("[UTF-8]: \n", raw.decode('utf-8'))
			except UnicodeDecodeError as e:
				log.print("[NOT UTF-8]: ", e.reason)

			msg = "Received!"
			msg += '\n'
			msg = msg.encode('utf-8')

			try:
				self.request.sendall(msg)
			except BrokenPipeError:
				log.print("[Time]:", datetime.datetime.now().strftime(datetime_format))
				log.print("[Error]: \n", "Broken Pipe Error.")
				break

	def finish(self):
		log.print("[Time]:", datetime.datetime.now().strftime(datetime_format))
		log.print("[Connection Closed]:\n", self.request)


if __name__ == '__main__':
	timespan = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
	if not os.path.exists(log_path):
		os.mkdir(log_path)
	log.bind(log_path + "/log_{}.log".format(timespan))

	with socketserver.ThreadingTCPServer((host, port), PortMonitorServer, bind_and_activate=False) as server:
		server.allow_reuse_address = True
		server.server_bind()
		server.server_activate()
		log.print("{0:*^50}".format(""))
		log.print("[Timestamp]: {}".format(datetime.datetime.now().strftime(datetime_format)))
		log.print("Server started, listening at %s:%s" % (host, port))

		try:
			server.serve_forever()
		except KeyboardInterrupt:
			log.print("{0:*^50}".format(""))
			log.print("[Timestamp]: {}".format(datetime.datetime.now().strftime(datetime_format)))
			log.print("\nServer shutdown.")
